//
//  WBStatusPictureView.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/6/8.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {
    
    var viewModel: WBStatusViewModel? {
        
        didSet {
            
            urls = viewModel?.picURLs
            
            calcViewSize()
        }
    }
    
    private func calcViewSize() {
        
        //单图，第一张图片宽度
        if viewModel?.picURLs?.count == 1 {
            let v = subviews[0]
            
            let viewSize = viewModel?.pictureViewSize ?? CGSize()
            
            v.frame = CGRect(x: 0, y: WBStatusPictureViewInnerMargin, width: viewSize.width, height: viewSize.height - 2 * WBStatusPictureViewInnerMargin)
        } else {
            
            //多图，第一张图片宽度
            let v = subviews[0]
            
            v.frame = CGRect(x: 0, y: WBStatusPictureViewInnerMargin, width: WBStatusPictureWidth, height: WBStatusPictureWidth)
        }
        
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
    }
    
    private var urls: [WBStatusPicture]? {
        
        didSet {
            for v in subviews {
                
                v.isHidden = true
            }
            
            var index = 0
            
            for url in urls ?? [] {
                
                let iv =  subviews[index] as! UIImageView
                
                // 4张图片时的处理
                if index == 1 && urls?.count == 4 {
                    
                    index += 1
                }
                
                iv.sc_setImage(urlString: url.thumbnail_pic, placeHolderImage:nil)
                
                iv.isHidden = false
                
                index += 1
            }
        }
    }

    @IBOutlet weak var heightCons: NSLayoutConstraint!

    override func awakeFromNib() {
        
        setupUI()
    }
    
}

extension WBStatusPictureView {
    
    fileprivate func setupUI() {
        
        backgroundColor = superview?.backgroundColor
        
        clipsToBounds = true
        
        let count = 3
        
        let rect = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureWidth, height: WBStatusPictureWidth)
        
        for i in 0..<count * count {
            
            let iv = UIImageView()
            
            iv.clipsToBounds = true
            
            iv.contentMode = .scaleAspectFill

            addSubview(iv)
            //计算frame
            let row = CGFloat (i / count)
            
            let col = CGFloat (i % count)
            
            let xOffset = col * (WBStatusPictureWidth + WBStatusPictureViewInnerMargin)
            
            let yOffset = row * (WBStatusPictureWidth + WBStatusPictureViewInnerMargin)
            
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
        }
    }
}
